import * as React from 'react';
// make React global, otherwise translated jsx will get a 'React not defined' error
window.React = React;
import AppRouter from './router';
import reducers from './reducers';
import { fetchMiddleware } from './actions/util';
import * as UserAction from './actions/user';
import { setStatusAction } from './agent';
import _ from 'lodash';
import ReactDOM from 'react-dom';
import * as Redux from 'redux';
import * as ReactRedux from 'react-redux';
import ReduxPromiseMiddleware from 'redux-promise';
import { init as wsHandlerInit } from './ws-handlers';

const store = Redux.createStore(reducers, Redux.compose(
  Redux.applyMiddleware(fetchMiddleware, ReduxPromiseMiddleware),
  window.devToolsExtension ? window.devToolsExtension() : f => f
));
const { Provider } = ReactRedux;

const loginPage = 'index';
const whiteList = ['index'];

const page = window.location.pathname.substring(1);

// dispatch logout action when 401 status received
setStatusAction(401, () => store.dispatch(UserAction.nativeLogout()), 1000);
// init all ws handlers
wsHandlerInit(store.dispatch);

store.dispatch(UserAction.getLogined())
  .then(({ payload: user }) => {
    if (_.isEmpty(user)) {
      // not in white list, redirect to login page
      if (!_.includes(whiteList, page)) {
        window.location.href = `/${loginPage}`;
        return;
      }
    }
    ReactDOM.render((
      <Provider store={store}>
        <AppRouter/>
      </Provider>
    ), document.getElementById('content'));
  });
